<template>
  <div class="image-uploader">
    <!-- 图片展示区域 -->
    <div class="image-preview" @click="handleClick">
      <img v-if="imageUrl" :src="imageUrl" alt="Preview" class="preview-image" />
      <span v-else class="placeholder">点击选择图片</span>
      <input ref="fileInput" type="file" accept="image/*" @change="handleFileChange" style="display: none;" />
    </div>

    <!-- 按钮区域 -->
    <div class="button-group">
      <el-button type="primary" @click="handleClick">选择图片</el-button>
      <el-button type="success" @click="uploadImage" :disabled="!imageUrl">上传图片</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { userUploadAvatarService } from '@/api/user.js';
import { useUserStore } from '@/stores/user';

// 响应式变量
const fileInput = ref(null); // 文件输入框引用
const selectedFile = ref(null); // 选中的文件
const imageUrl = ref(''); // 图片预览的 URL
const userStore = useUserStore();

// 点击图片区域时触发文件选择
const handleClick = () => {
  if (fileInput.value) {
    fileInput.value.click(); // 触发文件选择框
  }
};

// 处理文件选择变化
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    selectedFile.value = file;
    imageUrl.value = URL.createObjectURL(file); // 创建图片预览 URL
  } else {
    selectedFile.value = null;
    imageUrl.value = ''; // 清除图片预览
  }
};

// 将文件转换为 base64 编码
const fileToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};

// 上传图片
const uploadImage = async () => {
  if (!imageUrl.value) {
    ElMessage.warning('请选择一张图片');
    return;
  }

  try {
    // 将文件转换为 base64 字符串
    const base64String = await fileToBase64(selectedFile.value);

    // 调用 API 上传图片，传递 base64 字符串
    await userUploadAvatarService(base64String);

    // 更新用户信息
    await userStore.getUser();

    // 成功提示
    ElMessage.success('图片上传成功！');
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error('图片上传失败，请稍后再试。');
  }
};
</script>

<style scoped>
.image-uploader {
  text-align: center;
}

.image-preview {
  width: 200px;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
  overflow: hidden;
  position: relative;
}

.image-preview .preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.image-preview .placeholder {
  font-size: 14px;
  color: #999;
}

.button-group {
  display: flex;
  gap: 10px;
}
</style>
